<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>练习</title>
    <style>
      #empolyTable {
        margin: 0 auto;
      }
      th,
      td {
        border: 1px solid #333;
      }

      #add {
        width: 240px;
        margin: 40px auto;
        padding: 20px 10px 5px 10px;
        border: 1px solid #333;
      }

      span {
        display: inline-block;
        width: 50px;
      }
      button {
        display: block;
        margin: 5px auto;
      }
    </style>
  </head>
  <body>
    <table id="empolyTable">
      <thead>
        <tr>
          <th>Name</th>
          <th>Email</th>
          <th>Salary</th>
          <th>&nbsp;</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Tom</td>
          <td>tom@tom.com</td>
          <td>5000</td>
          <td><a href="deleteEmp?id=001">Delete</a></td>
        </tr>
        <tr>
          <td>Jerry</td>
          <td>tom@tom.com</td>
          <td>5000</td>
          <td><a href="deleteEmp?id=002">Delete</a></td>
        </tr>
        <tr>
          <td>Bob</td>
          <td>tom@tom.com</td>
          <td>5000</td>
          <td><a href="deleteEmp?id=003">Delete</a></td>
        </tr>
      </tbody>
    </table>

    <div id="add">
      <h4>添加新员工</h4>
      <span>name:</span><input id="name" type="text" /><br />
      <span>email:</span><input id="email" type="text" /><br />
      <span>salary:</span><input id="salary" type="text" /><br />
      <button id="submit">Submit</button>
    </div>

    <script>
      // 删除方法
      function delA() {
        var tr = this.parentNode.parentNode;
        var name = tr.getElementsByTagName("td")[0].innerHTML;
        var flag = confirm(`确认删除${name}吗？`);
        if (flag) {
          tr.parentNode.removeChild(tr);
        }

        return false;
      }

      // 删除
      var allA = document.getElementsByTagName("a");
      for (var i = 0; i < allA.length; ++i) {
        allA[i].onclick = delA;
      }

      // 新增
      var submit = document.getElementById("submit");
      submit.onclick = function () {
        var name = document.getElementById("name").value;
        var email = document.getElementById("email").value;
        var salary = document.getElementById("salary").value;

        var tbody = document.getElementsByTagName("tbody")[0];
        var tr = document.createElement("tr");
        tr.innerHTML = `<tr>
                <td>${name}</td>
                <td>${email}</td>
                <td>${salary}</td>
                <td><a href="deleteEmp?id=004">Delete</a></td>
              </tr>`;

        var a = tr.getElementsByTagName("a")[0];
        a.onclick = delA;
        tbody.appendChild(tr);
      };
    </script>
  </body>
</html>
